package sg.edu.nus.iss.umpire.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import sg.edu.nus.iss.umpire.dao.CompetitionDayDao;
import sg.edu.nus.iss.umpire.domain.CompetitionDay;
import sg.edu.nus.iss.umpire.domain.Session;

public class CompetitionDayDaoImpl extends BaseDaoImpl<Long, CompetitionDay>
		implements CompetitionDayDao {

	public CompetitionDayDaoImpl(EntityManager em) {
		super(em);
	}

	public void addSession(CompetitionDay competitionDay, Session session) {
		// TODO
		CompetitionDay p = (CompetitionDay) em.find(CompetitionDay.class,
				competitionDay.getCompetitionDayKey());
			if(p.getSessions() != null){
		        p.getSessions().add(session);
			}else{
				List<Session> sessionListObj = new ArrayList<Session>();
				sessionListObj.add(session);
				p.setSessions(sessionListObj);
			}
		em.merge(p);
	}
	
	public List<Session> listSession(CompetitionDay competitionDay) {
		// TODO
		List<Session> sessionList = new ArrayList<Session>();
		CompetitionDay p = (CompetitionDay) em.find(CompetitionDay.class, competitionDay.getCompetitionDayKey());
		sessionList = p.getSessions();
		return sessionList;
	}

	public List<CompetitionDay> findByCompetitionKey(Long competitionKey) {
			String query = "SELECT FROM " + CompetitionDay.class.getName()
					+ " competitionDay where competitionKey=:competitionKey ";
			Query q = em.createQuery(query).setParameter("competitionKey",
					competitionKey);
			q.setHint("datanucleus.appengine.datastoreReadConsistency",
					"EVENTUAL");
			List<CompetitionDay> competitionDayList = (List<CompetitionDay>) q
					.getResultList();
			return competitionDayList;
	}

}
